<template>
  <div class="class-container">
    <div class="page-header">
      <h2>班级管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          添加班级
        </el-button>
        <!-- <el-button type="success" @click="handleImport">
          <el-icon><Upload /></el-icon>
          批量导入
        </el-button>
        <el-button type="warning" @click="handleExport">
          <el-icon><Download /></el-icon>
          导出数据
        </el-button> -->
      </div>
    </div>
    
    <!-- 搜索筛选 -->
    <div class="search-section">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            v-model="searchForm.search"
            placeholder="请输入班级名称"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-col>
        <el-col :span="6">
          <el-select v-model="searchForm.grade" placeholder="选择年级" clearable>
            <el-option label="全部年级" value="" />
            <el-option label="2005级" value="2005" />
            <el-option label="2006级" value="2006" />
            <el-option label="2007级" value="2007" />
            <el-option label="2008级" value="2008" />
            <el-option label="2009级" value="2009" />
            <el-option label="2010级" value="2010" />
            <el-option label="2011级" value="2011" />
            <el-option label="2012级" value="2012" />
            <el-option label="2013级" value="2013" />
            <el-option label="2014级" value="2014" />
            <el-option label="2015级" value="2015" />
            <el-option label="2016级" value="2016" />
            <el-option label="2017级" value="2017" />
            <el-option label="2018级" value="2018" />
            <el-option label="2019级" value="2019" />
            <el-option label="2020级" value="2020" />
            <el-option label="2021级" value="2021" />
            <el-option label="2022级" value="2022" />
            <el-option label="2023级" value="2023" />
            <el-option label="2024级" value="2024" />
            <el-option label="2025级" value="2025" />
          </el-select>
        </el-col>
        <el-col :span="10">
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="success" @click="handleRefresh">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </el-col>
      </el-row>
    </div>
    
    <!-- 班级表格 -->
    <div class="class-table">
      <el-table
        :data="classList"
        v-loading="loading"
        stripe
        style="width: 100%"
        empty-text="暂无班级数据"
      >
        <el-table-column prop="name" label="班级名称" min-width="150" />
        <el-table-column prop="grade" label="年级" min-width="100" />
        <el-table-column prop="createdTime" label="创建时间" min-width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.createdTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="updatedTime" label="更新时间" min-width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.updatedTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    
    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑班级对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      :before-close="handleDialogClose"
    >
      <el-form
        ref="classFormRef"
        :model="classForm"
        :rules="classFormRules"
        label-width="80px"
      >
        <el-form-item label="班级名称" prop="name">
          <el-input
            v-model="classForm.name"
            placeholder="请输入班级名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="年级" prop="grade">
          <el-select
            v-model="classForm.grade"
            placeholder="请选择年级"
            style="width: 100%"
          >
            <el-option label="2005级" value="2005" />
            <el-option label="2006级" value="2006" />
            <el-option label="2007级" value="2007" />
            <el-option label="2008级" value="2008" />
            <el-option label="2009级" value="2009" />
            <el-option label="2010级" value="2010" />
            <el-option label="2011级" value="2011" />
            <el-option label="2012级" value="2012" />
            <el-option label="2013级" value="2013" />
            <el-option label="2014级" value="2014" />
            <el-option label="2015级" value="2015" />
            <el-option label="2016级" value="2016" />
            <el-option label="2017级" value="2017" />
            <el-option label="2018级" value="2018" />
            <el-option label="2019级" value="2019" />
            <el-option label="2020级" value="2020" />
            <el-option label="2021级" value="2021" />
            <el-option label="2022级" value="2022" />
            <el-option label="2023级" value="2023" />
            <el-option label="2024级" value="2024" />
            <el-option label="2025级" value="2025" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Upload,
  Download,
  Search,
  Refresh
} from '@element-plus/icons-vue'
import {
  getClassesApi,
  addClassApi,
  updateClassApi,
  deleteClassApi
} from '@/api/class/class'

// 响应式数据
const loading = ref(false)
const classList = ref([])

// 搜索表单
const searchForm = reactive({
  search: '',
  grade: ''
})

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const submitLoading = ref(false)
const classFormRef = ref()
const isEdit = ref(false)
const editId = ref(null)

// 班级表单
const classForm = reactive({
  name: '',
  grade: ''
})

// 表单验证规则
const classFormRules = {
  name: [
    { required: true, message: '请输入班级名称', trigger: 'blur' },
    { min: 1, max: 50, message: '班级名称长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  grade: [
    { required: true, message: '请选择年级', trigger: 'change' }
  ]
}

// 工具方法
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// API调用方法
const loadClassList = async () => {
  try {
    loading.value = true
    const params = {
      page: currentPage.value,
      page_size: pageSize.value,
      search: searchForm.search || undefined,
      grade: searchForm.grade || undefined
    }

    const response = await getClassesApi(params)
    if (response.code === 200) {
      classList.value = response.data.data || []
      total.value = response.data.totalCount || 0
      ElMessage.success(response.message || '获取班级列表成功')
    } else {
      ElMessage.error(response.message || '获取班级列表失败')
    }
  } catch (error) {
    console.error('获取班级列表失败:', error)
    ElMessage.error('获取班级列表失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  currentPage.value = 1
  loadClassList()
}

const handleReset = () => {
  Object.assign(searchForm, {
    search: '',
    grade: ''
  })
  handleSearch()
}

const handleRefresh = () => {
  loadClassList()
}

const handleAdd = () => {
  dialogTitle.value = '添加班级'
  isEdit.value = false
  Object.assign(classForm, {
    name: '',
    grade: ''
  })
  dialogVisible.value = true
}

const handleImport = () => {
  ElMessage.info('批量导入功能开发中...')
}

const handleExport = () => {
  ElMessage.info('导出数据功能开发中...')
}

const handleEdit = (row) => {
  dialogTitle.value = '编辑班级'
  isEdit.value = true
  editId.value = row.id
  Object.assign(classForm, {
    name: row.name,
    grade: row.grade
  })
  dialogVisible.value = true
}

const handleViewStudents = (row) => {
  ElMessage.info(`查看学生功能开发中... 班级：${row.name}`)
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除班级 "${row.name}" 吗？删除后该班级下的学生和成绩记录也将被删除，此操作不可逆！`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }
    )

    const response = await deleteClassApi(row.id)
    if (response.code === 200) {
      ElMessage.success(response.message || '删除成功')
      loadClassList()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除班级失败:', error)
      ElMessage.error('删除失败，请稍后重试')
    }
  }
}

const handleDialogClose = () => {
  dialogVisible.value = false
  classFormRef.value?.resetFields()
}

const handleSubmit = async () => {
  try {
    await classFormRef.value.validate()
    submitLoading.value = true

    let response
    if (isEdit.value) {
      response = await updateClassApi(editId.value, classForm)
    } else {
      response = await addClassApi(classForm)
    }

    if (response.code === 200) {
      ElMessage.success(response.message || `${isEdit.value ? '更新' : '添加'}成功`)
      handleDialogClose()
      loadClassList()
    } else {
      ElMessage.error(response.message || `${isEdit.value ? '更新' : '添加'}失败`)
    }
  } catch (error) {
    console.error(`${isEdit.value ? '更新' : '添加'}班级失败:`, error)
    ElMessage.error(`${isEdit.value ? '更新' : '添加'}失败，请稍后重试`)
  } finally {
    submitLoading.value = false
  }
}

const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  loadClassList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadClassList()
}

onMounted(() => {
  loadClassList()
})
</script>

<style lang="scss" scoped>
.class-container {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      color: #333;
    }
    
    .header-actions {
      display: flex;
      gap: 10px;
    }
  }
  
  .search-section {
    background: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    margin-bottom: 20px;
  }
  
  .class-table {
    background: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    margin-bottom: 20px;
    overflow-x: auto; // 添加水平滚动支持

    // 确保表格占满容器宽度
    :deep(.el-table) {
      width: 100%;
      min-width: 650px; // 设置最小宽度确保内容不会过度压缩
    }

    // 优化表格单元格内容显示
    :deep(.el-table__cell) {
      padding: 12px 8px;
    }
  }
  
  .pagination {
    display: flex;
    justify-content: center;
    padding: 20px 0;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .class-container {
    .page-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 15px;

      .header-actions {
        width: 100%;
        justify-content: flex-start;
        flex-wrap: wrap;
      }
    }

    .search-section {
      padding: 15px;

      .el-col {
        margin-bottom: 15px;
      }
    }

    .class-table {
      padding: 15px;

      // 移动端表格优化
      :deep(.el-table) {
        min-width: 500px; // 移动端减小最小宽度
        font-size: 14px;
      }

      // 操作按钮在移动端垂直排列
      :deep(.el-table__fixed-right) {
        .el-button {
          margin-bottom: 5px;
          display: block;
          width: 100%;
        }
      }
    }
  }
}
</style>
